package com.yuxin.tongyi.lsll.sub;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.yuxin.tongyi.lsll.R;
import com.yuxin.tongyi.lsll.util.DateFormatTool;

/**
 * 图片选择框
 *
 */
public class ShowPhotoDialog extends AlertDialog implements android.view.View.OnClickListener{
	private final String TAG = "StorePhotoListActivity";

	private ListView lvImageList;
	private Button btnSelect, btnBack;
	private Context context = null;
	
	private String imageID = "imageID";
	private String imageName = "imageName";
	private String imageSize = "imageSize";
	private String imageUri = "imageUri";
	private String imageDate = "imageDate";
	private ArrayList<String> fileNames = new ArrayList<String>();
	private MultipleChoiceImageListAdapter mAdapter;
	private ArrayList<Map<String, String>> picList;
	
	private ImageCallBack mImageCallBack;
	
	protected ShowPhotoDialog(Context context) {
		super(context);
		this.context = context;
	}
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_photo);

		initView();
		initData();
	}
	
	public void initView() {
		lvImageList = (ListView) this.findViewById(R.id.lvImageList);
		btnSelect = (Button) findViewById(R.id.sub_storephotolist_select);
		btnBack = (Button) findViewById(R.id.sub_storephotolist_back);
		
		btnSelect.setOnClickListener(this);
		btnBack.setOnClickListener(this);
		
		lvImageList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				CheckedTextView checkedTextView = (CheckedTextView) view.findViewById(R.id.photolistitem_chkname);
				checkedTextView.toggle();
				
				mAdapter.setCheckItem(position, checkedTextView.isChecked());
			}
		});
	}
	
	public void initData() {
		String[] from = { imageID, imageName, imageSize, imageDate };
		int[] to = { R.id.photolistitem_image, R.id.photolistitem_chkname, R.id.photolistitem_tvsize, R.id.photolistitem_tvdate };
		picList = GetImageList();
		mAdapter = new MultipleChoiceImageListAdapter(context, picList, R.layout.list_photo_item, from, to);
		lvImageList.setAdapter(mAdapter);
	}
	
	// 获取图片列表
	private ArrayList<Map<String, String>> GetImageList() {
		ArrayList<Map<String, String>> imageList = new ArrayList<Map<String, String>>();
		HashMap<String, String> imageMap;
		//读取SD卡中所有图片
		Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		String[] projection = { MediaStore.Images.Media._ID,
								MediaStore.Images.Media.DISPLAY_NAME,
								MediaStore.Images.Media.DATA, 
								MediaStore.Images.Media.DATE_MODIFIED,
								MediaStore.Images.Media.SIZE };
		String selection = MediaStore.Images.Media.MIME_TYPE + "=?";
		String[] selectionArg = { "image/jpeg" };
		Cursor mCursor = ((Activity) context).managedQuery(uri, projection, selection, selectionArg, MediaStore.Images.Media.DATE_MODIFIED);
		
		imageList.clear();
		if (mCursor != null) {
			mCursor.moveToFirst();
			while (mCursor.getPosition() != mCursor.getCount()) {
				imageMap = new HashMap<String, String>();
				imageMap.put(imageID, mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media._ID)));
				imageMap.put(imageName, mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME)));
				imageMap.put(imageSize, " "+ (mCursor.getLong(mCursor.getColumnIndex(MediaStore.Images.Media.SIZE)) / 1024) + "KB");
				imageMap.put(imageUri, mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA)));
				imageMap.put(imageDate, DateFormatTool.getShortDateByMillis(mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATE_MODIFIED))));
				imageList.add(imageMap);
				
				fileNames.add(mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA)));
				Log.i(TAG, "IMAGEID: " + mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media._ID)));
				Log.i(TAG, "imageUri: " + mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA)));
				Log.i(TAG, "imageUri: " + mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATE_MODIFIED)));
				mCursor.moveToNext();
			}
			mCursor.close();
		}
		return imageList;
	}
	
	/**
	 * 选择图片确定
	 */
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.sub_storephotolist_select: 
			long[] selecteds = mAdapter.getCheckItemIds();
			String message = "";
			if(selecteds!=null && selecteds.length>0) {
			    long selectId = selecteds[0];
			    //message = "温馨提示:您选择了第"+(selectId+1)+"张图片";
//				String name = GetImageList().get((int)selectId).get("imageName");
				String uri = picList.get((int)selectId).get("imageUri");
				if(uri!=null && !"".equals(uri)) {
					CaremaPhotoUploadActivity.uploadUrl = uri;
					CaremaPhotoUploadActivity.picId = String.valueOf(selectId);
					if(mImageCallBack != null){
						mImageCallBack.setImage(uri);
					}
				}
			}
			
			this.cancel();
			break;
		case R.id.sub_storephotolist_back:
			this.cancel();
			break;
		}
	}
	
	

	// 可多选图片列表适配器
	class MultipleChoiceImageListAdapter extends SimpleAdapter {
		private Map<Integer, Boolean> picStateMap;  //图片列表序号，是否选中
		private List<Integer> selectlist;   //选中项列表
		private List<? extends Map<String, ?>> mList;  // 图片列表
		LayoutInflater mInflater;

		public MultipleChoiceImageListAdapter(Context context, List<Map<String, String>> data, int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
			
			String selectedId = CaremaPhotoUploadActivity.picId;
			picStateMap = new HashMap<Integer, Boolean>();
			mInflater = LayoutInflater.from(context);
			mList = data;
			selectlist = new ArrayList<Integer>();
			
			for (int i = 0; i < data.size(); i++) {
				if(selectedId!=null && !"".equals(selectedId)) {
					if(Integer.parseInt(selectedId) == i) {
						picStateMap.put(i, true);
						selectlist.add(i);
					}else {
						picStateMap.put(i, false);
					}
				}else{
					picStateMap.put(i, false);
				}
			}
		}

		@Override
		public int getCount() {
			return mList.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		// 设置条目选中状态
		public void setCheckItem(int position, Boolean isChecked) {
			/*
			 * 实现多选逻辑
			 */
//			map.put(position, isChecked);
//			if (state.contains(position))
//				state.remove((Object) position);
//			if (isChecked) {
//				state.add(position);
//			}
			
			
			/**
			 *实现单选逻辑
			 */
			if(selectlist!=null && !selectlist.isEmpty()) {
				for(int i=0; i<selectlist.size(); i++) { //将所有选中的取消
					Integer it = selectlist.get(i);
					picStateMap.put(it,false);
				}
			}

			selectlist.clear();
			picStateMap.put(position,isChecked);
			if (isChecked) {
				selectlist.add(position);
		    }
		}

		// 获取列表中已选中条目
		public long[] getCheckItemIds() {
			int count = selectlist.size();
			long[] ids = new long[count];
			for (int i = 0; i < count; i++) {
				ids[i] = (long) selectlist.get(i);
			}
			return ids;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.list_photo_item, null);
			}
			//图片名称
			CheckedTextView checkedTextView = (CheckedTextView) convertView.findViewById(R.id.photolistitem_chkname);
			checkedTextView.setChecked(picStateMap.get(position));
			checkedTextView.setText((String) mList.get(position).get(imageName));
			//图片size
			TextView tvSize = (TextView) convertView.findViewById(R.id.photolistitem_tvsize);
			tvSize.setText((String) mList.get(position).get(imageSize));
			//显示图片缩略图
			ImageView image = (ImageView) convertView.findViewById(R.id.photolistitem_image);
			Bitmap bm = MediaStore.Images.Thumbnails.getThumbnail(context.getContentResolver(),
					Long.parseLong((String) mList.get(position).get(imageID)),
					Images.Thumbnails.MICRO_KIND, null);
			image.setImageBitmap(bm);
			//图片日期
			TextView tvDate = (TextView) convertView.findViewById(R.id.photolistitem_tvdate);
			tvDate.setText((String) mList.get(position).get(imageDate));
			
			return convertView;
		}
	}
	
	public interface ImageCallBack{
		public void setImage(String uri);
	}
	
	public void setImageCallBack(ImageCallBack imagecb){
		mImageCallBack = imagecb;
	}
}
